package com.zretc.support.service.serviceimpl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zretc.support.constant.CommonConstant;
import com.zretc.support.entity.Online;
import com.zretc.support.entity.User;
import com.zretc.support.service.ChatSessionService;
import com.zretc.support.service.OnlineService;
import com.zretc.support.tool.CoreUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ChatSessionServiceImpl implements ChatSessionService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OnlineService onlineService;

    Logger logger = LoggerFactory.getLogger(ChatSessionServiceImpl.class);

    /**
     * 根据用户电话在redis里查找
     * @param id
     * @return
     */
    @Override
    public User findById(String id) {
        if(id != null){
            String value = null;
            if(id.startsWith(CommonConstant.USER_PREFIX)){
                value = redisTemplate.boundValueOps(id).get();
            }else{
                value = redisTemplate.boundValueOps(CommonConstant.USER_PREFIX + id).get();
            }
            JSONObject object = JSONObject.parseObject(value);
            if(object != null){
                User u = object.toJavaObject(User.class);
                return u;
            }
        }
        return null;
    }

    /**
     * 发送消息 -》 私聊/群聊
     * @param fromId  推送方ID
     * @param toId    接收方ID
     * @param message 消息
     */
    @Override
    public void pushMessage(String fromId, String toId, String message) {
        Online online = new Online();
        online.setOnlineMessage(message);
        online.setSender(this.findById(fromId));
        online.setOnlineDate(new Date());
        if(toId != null){
            // 私聊
            online.setReceiver(this.findById(toId));
            // 私聊信息存在数据库
            onlineService.addOnline(online);
            push(online,CommonConstant.CHAT_FROM_PREFIX + fromId + CommonConstant.CHAT_TO_PREFIX + toId);
        }else{
            // 群聊
            online.setReceiver(null);
            push(online,CommonConstant.CHAT_COMMON_PREFIX + fromId);
        }
    }

    /**
     * 在线用户
     * @return
     */
    @Override
    public List<User> onlineList() {
        List<User> list = new ArrayList<>();
        Set<String> keys = redisTemplate.keys(CommonConstant.USER_PREFIX + CommonConstant.REDIS_MATCH_PREFIX);
        if(keys != null && keys.size() > 0){
            keys.forEach(key -> {
                list.add(this.findById(key));
            });
        }
        return list;
    }

    /**
     * 公聊消息
     * @return
     */
    @Override
    public List<Online> commonList() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<Online> list = new ArrayList<>();
        // CHAT_COMMON_ + *   --> 模糊匹配
        Set<String> keys = redisTemplate.keys(CommonConstant.CHAT_COMMON_PREFIX + CommonConstant.REDIS_MATCH_PREFIX);
        if (keys != null && keys.size() > 0) {
            keys.forEach(key -> {
                String value = redisTemplate.boundValueOps(key).get();
                List<Online> messageList = Objects.requireNonNull(JSONObject.parseArray(value)).toJavaList(Online.class);
                list.addAll(messageList);
            });
        }
        CoreUtil.sort(list);
        return list;
    }

    /**
     * 私聊消息
     * @param fromId 推送方ID
     * @param toId   接收方ID
     * @return
     */
    @Override
    public List<Online> selfList(String fromId, String toId) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<Online> list = new ArrayList<>();
        String fromTo = redisTemplate.boundValueOps(CommonConstant.CHAT_FROM_PREFIX + fromId + CommonConstant.CHAT_TO_PREFIX + toId).get();

        String toFrom = redisTemplate.boundValueOps(CommonConstant.CHAT_FROM_PREFIX + toId + CommonConstant.CHAT_TO_PREFIX + fromId).get();

        JSONArray fromToObject = JSONObject.parseArray(fromTo);
        JSONArray toFromObject = JSONObject.parseArray(toFrom);

        if(fromToObject != null){
            list.addAll(fromToObject.toJavaList(Online.class));
        }
        if(toFromObject != null){
            list.addAll(toFromObject.toJavaList(Online.class));
        }

        if (list.size() > 0){
            CoreUtil.sort(list);
            return list;
        }else{
            return new ArrayList<>();
        }
    }

    /**
     * 注销
     * @param id
     */
    @Override
    public void delete(String id) {
        if(id != null){
            redisTemplate.delete(CommonConstant.USER_PREFIX + id);
        }
    }

    /**
     * 发消息 -- 存到redis中
     * @param online
     * @param key
     */
    private void push(Online online,String key){
        List<Online> list = new ArrayList<>();
        String value = redisTemplate.boundValueOps(key).get();
        if(value == null){
            // 第一次发消息
            list.add(online);
        }else{
            // 第n次发消息
            list = Objects.requireNonNull(JSONObject.parseArray(value)).toJavaList(Online.class);
            list.add(online);
        }
        redisTemplate.boundValueOps(key).set(JSONObject.toJSONString(list));
    }

}
